<?php

class Admin_TymPresenter extends BasePresenter
{	
	public function renderDefault()
	{
		$tym = new TymModel();
		$this->template->tymy = $tym->findAll();
	}
	
	public function renderNovy()
	{
		$form = $this['tymForm'];
	}
	public function renderUpravit($id = 0)
	{
		$form = $this['tymForm'];
		
		if (!$form->isSubmitted()) {
			$tym = new TymModel();			
			$row = $tym->findById($id)->fetch();
			$this->template->image = $row['logo'];
			if (!$row) {
				throw new NBadRequestException('Záznam nebyl nalezen.');
			}
			$form->setDefaults($row);
		}
	}
	
	public function renderSmazat($id = 0)
	{
		$tym = new TymModel();
		$this->template->tym = $tym->findById($id)->fetch();

		if (!$this->template->tym) {
			throw new NBadRequestException('Tým nebyl nalezen.');
		}
	}
	
	protected function createComponentSmazatForm()
	{
		$form = new NAppForm;
		
		$form->addSubmit('delete', 'Smazat')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět');
		$form->onSubmit[] = callback($this, 'smazatFormSubmitted');
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		return $form;
	}
	
	public function smazatFormSubmitted(NAppForm $form)
	{
		if ($form['delete']->isSubmittedBy()) {
			$tym = new TymModel();
			$id = $this->getParam('id');
			$image_name = $tym->findById($id)->fetch();
			@unlink('./images/loga/'.$image_name['logo']);
			$tym->delete($id);
			$this->flashMessage('Tým byl odstraněn.');
		}

		$this->redirect('default');
	}
	
	protected function createComponentTymForm()
	{
		$form = new NAppForm;
		$form->addText('nazev', 'Název:');
		$form->addText('stat', 'Stát:');
		$form->addText('mesto', 'Město:');
		$form->addText('ulice', 'Ulice:');
		$form->addText('psc', 'PSČ:');
		$form->addText('telefon', 'Telefon:');
		$form->addText('email', 'E-mail:');
		$form->addText('www', 'WWW:');
		$form->addText('manazer', 'Manažer:');
		$form->addFile('logo', 'Logo:');
		$form->addSubmit('save', 'Uložit')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět')->getControlPrototype()->class('cancel')->setValidationScope(NULL);
		$form->onSubmit[] = callback($this, 'tymFormSubmitted');
		
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		$this->template->form = $form;
		return $form;
	}
	public function tymFormSubmitted(NAppForm $form)
	{
		if ($form['save']->isSubmittedBy()) {
			$id = (int) $this->getParam('id');
		
			$image = $form['logo']->value;
			$tym = new TymModel();
			if ($id > 0) {
				$nazev = $this->uploadImages($id, $image, 'update');
				if($nazev == ''){
					$image_name = $tym->findById($id)->fetch();
					$nazev = $image_name['logo'];
				}
				
				$values = array(
					'nazev'=>$form['nazev']->value,
					'stat'=>$form['stat']->value,
					'mesto'=>$form['mesto']->value,
					'ulice'=>$form['ulice']->value,
					'psc'=>$form['psc']->value,
					'telefon'=>$form['telefon']->value,
					'email'=>$form['email']->value,
					'www'=>$form['www']->value,
					'manazer'=>$form['manazer']->value,
					'logo'=>$nazev
				);
				$tym->update($id, $values);
				
				$this->flashMessage('Tým byl upraven.');
			} else {

				$values = array(
					'nazev'=>$form['nazev']->value,
					'stat'=>$form['stat']->value,
					'mesto'=>$form['mesto']->value,
					'ulice'=>$form['ulice']->value,
					'psc'=>$form['psc']->value,
					'telefon'=>$form['telefon']->value,
					'email'=>$form['email']->value,
					'www'=>$form['www']->value,
					'manazer'=>$form['manazer']->value,
					'logo'=>'noimage.jpg'
				);
				
				$tym->insert($values);
				$id = dibi::getInsertId();
				$nazev = $this->uploadImages($id, $image);
				$tym->update($id, array('logo'=>$nazev));
				$this->flashMessage('Tým byl vytvořen.');
			}
		}

		$this->redirect('default');
	}
	public function uploadImages($id, $image, $operation = 'insert'){


		if($image->isOk()){
			$mimeType = $_FILES['logo']['type'];
			switch($mimeType){
				case 'image/jpeg': $type = ".jpg";
				break;
				case 'image/gif': $type = ".gif";
				break;
				case 'image/png': $type = ".png";
				break;
				case 'image/tif': $type = ".tif";
				break;
				case 'image/tiff': $type = ".tiff";
				break;
				case 'image/bmp': $type = ".bmp";
				break;
			}

			$uploaddir = WWW_DIR . '/images/loga/';
			$filesMain = scandir(WWW_DIR.'/images/loga');
			$name = $id;    
			if($operation == 'update'){
				$tym = new TymModel();
				$image_name = $tym->findById($id)->fetch();
				@unlink('../images/logo/'.$image_name['logo']);
			}
			$uploadfile = $uploaddir . $name . $type;
			$image = NImage::fromFile($_FILES['logo']['tmp_name']);
			$image->resize(200, 200);
			$image->alphaBlending(false);
			$image->saveAlpha(true);
			$image->save($path = $uploadfile);
			chmod($uploadfile, 0777);
			return $name.$type;
		}
	}
	
	
	/* TYM_LIDE */
	
	
	public function renderLideDefault()
	{
		$tym = new TymModel();
		$lide = new LideModel();
		$pozice = new PoziceModel();
		$tym_lide_all = $tym->tym_lide_findAll()->fetchAll();
		foreach($tym_lide_all as $item){
			$tmp_tym = $tym->findById($item['tym_id'])->fetch();
			$item['tym_nazev'] = $tmp_tym['nazev'];
			$tmp_lide = $lide->findById($item['lide_id'])->fetch();
			$item['clovek_jmeno'] = $tmp_lide['jmeno'].' '.$tmp_lide['prijmeni'];
			$tmp_pozice = $pozice->findById($item['pozice_id'])->fetch();
			$item['pozice_nazev'] = $tmp_pozice['nazev'];
		}
		
		$this->template->lide = $tym_lide_all;

	}
	protected function createComponentHraciForm($name)
	{
		$soutez = new SoutezModel();
		$pozice = new PoziceModel();
		$lide = new LideModel();
		$form = new NAppForm($this, $name);
		$soutez_items = $soutez->findAll()->fetchPairs('id','nazev');
		$form->addSelect("soutez_id", "Soutěž:", $soutez_items)->skipFirst('Zvolte soutěž');
		$form->addDependentSelectBox("tym_id", "Tým:", $form["soutez_id"], callback($this, "getValuesTymy"))->skipFirst('Zvolte tým');
		if($this->isAjax())
			$form["tym_id"]->addOnSubmitCallback(callback($this, "invalidateControl"), "formSnippet");
		$lide_items = $lide->findAll()->fetchPairs('id','prijmeni');
		$form->addSelect('lide_id', 'Lidé:', $lide_items)->skipFirst('Zvolte člověka');
		$pozice_items = $pozice->findAll()->fetchPairs('id','nazev');
		$form->addSelect('pozice_id', 'Pozice:', $pozice_items)->skipFirst('Zvolte pozici');
		$form->addText('cislo_dresu', 'Číslo dresu:');
		$form->addTextArea('poznamky', 'Pozámky:');
		$form->addSubmit('save', 'Uložit')->getControlPrototype()->class('default');
		$form['save']->onClick[] = callback($this, "hraciFormSubmitted");		
		$form->addSubmit('cancel', 'Zpět')->setValidationScope(NULL);
		$form['cancel']->onClick[] = callback($this, "hraciFormSubmitted");
		
		
		
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		return $form;
	}
	public function hraciFormSubmitted($button)
	{	
		
		if(isset($button->form->httpData['save'])){
			$values = array(
				'tym_id'=>$button->form['tym_id']->value,
				'lide_id'=>$button->form['lide_id']->value, 
				'cislo_dresu'=>$button->form['cislo_dresu']->value, 
				'poznamky'=>$button->form['poznamky']->value, 
				'pozice_id' => $button->form['pozice_id']->value
			);
			
			
			$hraci = new TymModel();
			$hraci->tym_lide_insert($values);
			$this->flashMessage('Hráč byl přidán.');
			
		}

		$this->redirect('lideDefault');
	}
	
	public function renderLideSmazat($id = 0)
	{
		$hrac = new TymModel();
		$this->template->hrac = $hrac->tym_lide_findById($id)->fetch();

		if (!$this->template->hrac) {
			throw new NBadRequestException('Hráč nebyl nalezen.');
		}
	}
	
	protected function createComponentHraciSmazatForm()
	{
		$form = new NAppForm;
		
		$form->addSubmit('delete', 'Smazat')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět');
		$form->onSubmit[] = callback($this, 'hraciSmazatFormSubmitted');
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		return $form;
	}
	
	public function hraciSmazatFormSubmitted(NAppForm $form)
	{
		if ($form['delete']->isSubmittedBy()) {
			$lide = new TymModel();
			$id = $this->getParam('id');
			$lide->tym_lide_delete($id);
			$this->flashMessage('Hráč byl odebrán z týmu.');
		}

		$this->redirect('lideDefault');
	}
	
	public function getValuesTymy($form) {
				$soutez_id = $form["soutez_id"]->getValue();
		$tym = new TymModel();
		$tmp_tym = dibi::query("SELECT [*] FROM dbo.Tym_Soutez WHERE soutez_id=%i", $soutez_id)->fetchAll();
		$tym_assoc = array();
		foreach($tmp_tym as $item){
			$tmp_tym_nazev = $tym->findById($item['tym_id'])->fetch();
			$tym_assoc[$item['tym_id']] = $tmp_tym_nazev['nazev'];
		}
		
		return $tym_assoc;
	}

}

